package com.utils.office;

import org.apache.poi.POIXMLDocument;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.xwpf.converter.core.FileURIResolver;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

/**
 * Created by rain on 2017/4/14.
 */
public class WordConvertToHtml {

    /**
     * docx
     */
    private static String convertWordDocXtoHTML(String path) throws Exception {
        InputStream in = new FileInputStream(new File(path));
        XWPFDocument document = new XWPFDocument(in);
        XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(new File("word/media")));
        OutputStream out = new ByteArrayOutputStream();
        XHTMLConverter.getInstance().convert(document, out, options);
        String html = out.toString();
        return html;
    }

    /**
     * doc
     */
    private static String convertWordDocToHTML(InputStream inputStream) throws Exception {
        HWPFDocument doc = new HWPFDocument(inputStream);
        Document newDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(newDocument);
        wordToHtmlConverter.processDocument(doc);

        StringWriter stringWriter = new StringWriter();
        Transformer transformer = TransformerFactory.newInstance()
                .newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        transformer.setOutputProperty(OutputKeys.METHOD, "html");
        transformer.transform(new DOMSource(wordToHtmlConverter.getDocument()), new StreamResult(stringWriter));

        return stringWriter.toString();
    }

    public static String readWordFile(String file) throws Exception {
        FileInputStream in = null;
        String docContent = null;
        try {
            in = new FileInputStream(file);
            XWPFWordExtractor docx = new XWPFWordExtractor(POIXMLDocument.openPackage(file));
            docContent = docx.getText();
        } catch (Exception e) {
            e.getMessage();
        } finally {
            if (in != null) {
                in.close();
            }
        }
        return docContent;
    }
}
